using System;
using CastleSample.Business.Interface;
using CastleSample.Core;
using CastleSample.Entity;

namespace CastleSample.Business.Service
{
    public class MembershipBizService : BizServiceBase, IMembershipBizService
    {
        public UserContext UserLogin(string userName, string password)
        {
            LogService.InfoFormat(GetType().FullName, "UserLogin with {0} / {1}", userName, password);

            if (string.IsNullOrEmpty(userName.Trim()))
            {
                throw new ArgumentNullException("userName");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            if (!password.StartsWith("1"))
            {
                LogService.WarnFormat(GetType().FullName, "UserLogin failed with {0} / {1}", userName, password);
                return null;
            }

            UserContext context = new UserContext();
            context.UserName = userName.Trim();
            context.AuthenticationToken = userName.Trim() + password.Trim();
            context.OnlineMode = false;
            context.LoggedIn = true;

            LogService.InfoFormat(GetType().FullName, "UserLogin success with {0} / {1}", userName, password);
            return context;
        }

        public UserContext UserLogout(UserContext userContext)
        {
            LogService.InfoFormat(GetType().FullName, "UserLogout for {0}", userContext);
            if (!userContext.LoggedIn)
            {
                return userContext;
            }

            userContext.Reset();
            return userContext;
        }

        public bool IsUserTokenValid(UserContext userContext)
        {
            LogService.InfoFormat(GetType().FullName, "CheckUserToken for {0}", userContext);
            return userContext.AuthenticationToken.StartsWith(userContext.UserName);
        }
    }
}